package cn.gson.crmdemo.model.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;

import cn.gson.crmdemo.model.dao.CaigouDao;
import cn.gson.crmdemo.model.dao.CaigoumxDao;
import cn.gson.crmdemo.model.dao.CpDao;
import cn.gson.crmdemo.model.dao.EmpDao;
import cn.gson.crmdemo.model.dao.SupplierDao;
import cn.gson.crmdemo.model.mapper.CaigouMapper;
import cn.gson.crmdemo.model.pojo.Emp;
import cn.gson.crmdemo.model.pojo.Outorder;
import cn.gson.crmdemo.model.pojo.ProcurementDetail;
import cn.gson.crmdemo.model.pojo.Product;
import cn.gson.crmdemo.model.pojo.Purchase;
import cn.gson.crmdemo.model.pojo.Supplier;
import cn.gson.crmdemo.model.vo.ProcurementDetailsVo;

@Service
@Transactional(rollbackFor=Exception.class)
public class CaigouService {
	@Autowired
	CaigouDao Caigou;
	@Autowired
	CpDao cpdao;
	@Autowired
	CaigoumxDao cmdao;
	@Autowired
	SupplierDao sdao;
	@Autowired
	EmpDao edao;
	@Autowired
	CaigouMapper Caigou1;
	/*
	 * 查询采购单
	 */
	public JSONArray selectPurchase(String purchaseNo) {
		return Caigou1.selectPurchase(purchaseNo);
	}
	/*
	 * 模糊查询
	 */
	public JSONArray selectmhcx(String no) {
		return Caigou1.selectmhcx(no);
	}
	/*
	 * 新增采购单
	 */
	
	public void addcgd(List<ProcurementDetailsVo> cgmx,String empName) {
		Purchase cgd = new Purchase();
		cgd.setPurchaseDate(new Date());
		cgd.setPurchaseState(0);
		cgd.setPurchaseEmpId(empName);
		cgd.setPurchaseNo(caigouSj());
		cgd.setCpId(cgmx.get(0).getCpId());
		cgd.setPurchaseTheme(cgmx.get(0).getPurchaseTheme());
		cgd.setPurchaseMoney(cgmx.get(0).getPurchaseMoney());
		cgd.setPurchaseYfmoney(cgmx.get(0).getPurchaseYfmoney());
		cgd.setSupplier(sdao.findById(cgmx.get(0).getGysId()).get());
		Purchase save = Caigou.save(cgd);
		List<Integer> list = Caigou1.selectcgdmaxId();
		Purchase p = Caigou.findById(list.get(0)).get();
		for(int i=0;i<cgmx.size();i++) {
			ProcurementDetail pd = new ProcurementDetail();
			Product product = cpdao.findById(cgmx.get(i).getCpId()).get();
			pd.setProduct1(product);
			pd.setPdNumber(cgmx.get(i).getPdNumber());
			pd.setPdPrice(cgmx.get(i).getPdPrice());
			pd.setPurchase(p);
			cmdao.save(pd);
		}
	}

	/**
	 * 生成订单随机数 时间+随机数
	 * @return
	 */
	public String caigouSj() {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String newDate=sdf.format(new Date());
		String result="";
		Random random=new Random();
		for(int i=0;i<3;i++){
			result+=random.nextInt(10);
		}
		return newDate+result;
	}
	
	/*
	 *修改 
	 */
	public void xg(Purchase cgd) {
		Caigou.save(cgd);
	}
}
